package com.lungle.warmdiary.app.view.active.fragment;

import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.widget.MySwipeRefreshLayout;
import android.text.Html;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lungle.warmdiary.R;
import com.lungle.warmdiary.app.AppConstant;
import com.lungle.warmdiary.app.AppContext;
import com.lungle.warmdiary.app.api.HttpHelper;
import com.lungle.warmdiary.app.api.remote.ApiFactory;
import com.lungle.warmdiary.app.base.BaseDetailFragment;
import com.lungle.warmdiary.app.base.BaseSubscriber;
import com.lungle.warmdiary.app.model.Entity;
import com.lungle.warmdiary.app.model.Result;
import com.lungle.warmdiary.app.model.event.ActiveCommentRefreshEvent;
import com.lungle.warmdiary.app.model.event.ActiveStatueRefreshEvent;
import com.lungle.warmdiary.app.model.request.ActivePost;
import com.lungle.warmdiary.app.model.request.FollowPost;
import com.lungle.warmdiary.app.model.response.Active;
import com.lungle.warmdiary.app.model.response.ActiveState;
import com.lungle.warmdiary.app.model.response.Comment;
import com.lungle.warmdiary.app.ui.dialog.CommonToast;
import com.lungle.warmdiary.app.ui.empty.EmptyLayout;
import com.lungle.warmdiary.app.ui.guide.TextImageLayout;
import com.lungle.warmdiary.app.ui.widget.AutoGridView;
import com.lungle.warmdiary.app.utils.DateUtil;
import com.lungle.warmdiary.app.utils.FileUtils;
import com.lungle.warmdiary.app.utils.LogUtils;
import com.lungle.warmdiary.app.utils.ShareUtils;
import com.lungle.warmdiary.app.utils.UIHelper;
import com.lungle.warmdiary.app.view.IPagerFragment;
import com.lungle.warmdiary.app.view.active.adapter.ActiveImageAdapter;
import com.lungle.warmdiary.app.view.guideview.Guide;
import com.lungle.warmdiary.app.view.guideview.GuideBuilder;
import com.lungle.warmdiary.app.view.guideview.SimpleComponent;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.iwf.photopicker.PhotoPreview;
import okhttp3.ResponseBody;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class ActiveDetailFragment extends BaseDetailFragment implements AdapterView.OnItemClickListener, View.OnClickListener {
    private static final String ACTIVE_DETAIL_SCREEN = "active detail screen";

    public static final int CODE_REQUEST = 0;
    public static final int CODE_REPONSE_EXECUTE = 0;
    public static final int CODE_RESPONSE_COMMENT = 1;
    public static final int CODE_RESPONSE_DETAIL = 2;

    public static final String ARGS_RESPONSE = "actvie";

    private Handler handler;
    private Guide guide;

    @Bind(R.id.tv_advertiser)
    TextView mTvAdvertiser;
    @Bind(R.id.btn_follow)
    Button mBtnFollow;
    @Bind(R.id.tv_active_title)
    TextView mTvTitle;
    @Bind(R.id.tv_active_reward)
    TextView mTvReward;
    @Bind(R.id.iv_active_reward)
    ImageView ivReward;
    @Bind(R.id.tv_active_time)
    TextView mTvTime;
    @Bind(R.id.tv_active_append_num)
    TextView mTvAppendNum;
    @Bind(R.id.tv_active_channel)
    TextView mTvChannel;
    @Bind(R.id.tv_active_payment)
    TextView mTvPayment;
    @Bind(R.id.btn_reject_active)
    Button mBtnReject;
    @Bind(R.id.btn_receive_active)
    Button mBtnReceive;
    @Bind(R.id.gv_active)
    AutoGridView mGvActive;
    @Bind(R.id.tv_active_content)
    TextView mTvContent;
    Button mBtnDownloadImages;
    @Bind(R.id.btn_direct_share)
    Button mBtnDirectShare;
    @Bind(R.id.tv_execute_num)
    TextView mTvActiveExecute;
    @Bind(R.id.rl_active_execute_screenshot)
    RelativeLayout mRlExecuteScreenshot;
    @Bind(R.id.tv_comment_num)
    TextView mTvCommentNum;
    @Bind(R.id.rl_active_num_screenshot)
    RelativeLayout mRlNumScreenshot;
    @Bind(R.id.tv_detail_num)
    TextView mTvDetail;
    @Bind(R.id.rl_active_detail_screenshot)
    RelativeLayout mRlDetailScreenshot;
    @Bind(R.id.ll_comment_container)
    LinearLayout mllCommentContainer;
    @Bind(R.id.sv_active_container)
    ScrollView svActiveContainer;
    @Bind(R.id.tv_active_commentor)
    TextView mTvActiveCommentor;
    @Bind(R.id.tv_comment_content)
    TextView mTvCommentContent;
    @Bind(R.id.btn_view_all_commments)
    Button mBtnViewAllCommments;
    @Bind(R.id.rl_active_help)
    RelativeLayout rlActiveHelp;
    @Bind(R.id.tv_link)
    TextView mTvLink;

    @Bind(R.id.ll_active_operator)
    LinearLayout mLLActive_Operator;
    @Bind(R.id.tv_link_text)
    TextView mTvLinkText;
    @Bind(R.id.srl_refresh)
    MySwipeRefreshLayout srlRefresh;
    @Bind(R.id.error_layout)
    EmptyLayout errorLayout;

    @Bind(R.id.guide_ui)
    TextImageLayout textImageLayout;


    private Active mActive;
    private String mActiveId;
    private String mMediaId;

    //    private PopupWindow mImagePreviewPop;
    //    private ProgressBar mPbLoading;
    //
    //    private ImageView mIvPreview;

    private List<String> mImages = new ArrayList<>();

    private List<String> imageFile = new ArrayList<>();
//    private ImagePreview mImagePreview;

    //    private List<String> hasDownload = new ArrayList<>();


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_active_detail;
    }

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(getLayoutId(), container, false);
        initData();
        initViews(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(ACTIVE_DETAIL_SCREEN);
        MobclickAgent.onResume(getActivity());

    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(ACTIVE_DETAIL_SCREEN);
        MobclickAgent.onPause(getActivity());

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
        }
        if (guide != null) {
            guide.dismiss();
            guide = null;
        }

    }

    @Override
    public void initData() {
        mActiveId = getActivity().getIntent().getStringExtra("active_id");
        mMediaId = getActivity().getIntent().getStringExtra("media_id");
    }


    private void initViews(View view) {
        ButterKnife.bind(this, view);
        //        initPicturePreview(view);
//        mImagePreview = new ImagePreview(getActivity());


    }

    @Override
    protected void sendRequestData() {
        ApiFactory.getUserApi().getActiveDetail(mActiveId, mMediaId).subscribeOn(Schedulers.io())
                .compose(this.<Result>bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(getSubscriber());

    }

    @Override
    protected void executeOnLoadDataSuccess(Entity entity) {
        mActive = (Active) entity;
        String link = mActive.getLink();
        if (!TextUtils.isEmpty(mActive.getShortLink()))
            link = mActive.getShortLink();
        nofityCommnetFragment(mActive.getReviewGroupId(), mActive.getStatus(), link, mActive.getLinkText(), mActive.getProductid());
        fillUI();
    }

    private void fillUI() {
        mTvAdvertiser.setText(mActive.getAdvertiser());
        mTvTitle.setText(mActive.getName());
        SpannableString ss = new SpannableString(String.format("%s人", mActive.getNengage()));
        ss.setSpan(new ForegroundColorSpan(Color.RED), 0, (0 + "").length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(Color.GRAY), ss.length() - 1, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTvAppendNum.setText(ss);


        Resources res = getApplication().getResources();
        Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.ic_wechat_friend);
        mTvChannel.setCompoundDrawablesWithIntrinsicBounds(new BitmapDrawable(res, bitmap), null, null, null);
        mTvChannel.setText(mActive.getMeida());


        if (mActive.getChargeType() == Active.PAYMENT_EFFECT) {
            if (mActive.getLimitType() != null && mActive.getLimitType().equals(Active.LIMT_TYPE_CONVERT_NUM)) {
                mTvPayment.setText(getPaymentOnEffect("转化", mActive.getPrice(), mActive.getIndividualLimit(), mActive.getTotalLimit()));
            } else if (mActive.getLimitType() != null && mActive.getLimitType().equals(Active.LIMT_TYPE_CLICK_NUM)) {
                mTvPayment.setText(getPaymentOnEffect("点击", mActive.getPrice(), mActive.getIndividualLimit(), mActive.getTotalLimit()));
            }

        } else if (mActive.getChargeType() == Active.PAYMENT_PRICE) {
            String chargeCondition = mActive.getChargeCondition();
            JsonObject jsonObject = new JsonParser().parse(chargeCondition).getAsJsonObject();
            int nclick = jsonObject.has("nclick") ? jsonObject.get("nclick").getAsInt() : 0;
            int ncomment = jsonObject.has("ncomment") ? jsonObject.get("ncomment").getAsInt() : 0;
            int nlike = jsonObject.has("nlike") ? jsonObject.get("nlike").getAsInt() : 0;
            mTvPayment.setText(getPaymentOnPrice(nclick, ncomment
                    , nlike, mActive.getPrice()));
        }


        mTvReward.setText(mActive.getBudget() + "");
        mTvTime.setText("活动时间: " + mActive.getStarttime() + "至" + mActive.getEndtime());


//        String html ="<a href='http://www.baidu.com'>百度一下</a>";
        Spanned spanned = Html.fromHtml(String.format("<a href='%s'>%s</a>", mActive.getLink(), mActive.getLinkText()));
        mTvLinkText.setText(spanned);
//        mTvLinkText.setText(mActive.getLinkText() + ":");


//        if (!TextUtils.isEmpty(mActive.getShortLink())) {
//            mTvLink.setText(mActive.getShortLink());
//        } else {
//        mTvLink.setText(mActive.getLink());
//        }


        mTvContent.setText(mActive.getDesc());
        mTvActiveExecute.setText(getExecuteNum(mActive.getPublishScreenshot() != null ? 1 : 0));
        mTvCommentNum.setText(getCommentNum(mActive.getNlike(), mActive.getNcomment()));

        int num = (mActive.getResultScreenshot2() != null ? mActive.getResultScreenshot2().size() : 0);
        mTvDetail.setText(getDetailNum(num));

        List<Active.ProductReviewsBean> productReviews = mActive.getProductReviews();

        if (productReviews != null && productReviews.size() != 0) {
            Active.ProductReviewsBean productReviewsBean = mActive.getProductReviews().get(0);
            mTvActiveCommentor.setText(productReviewsBean.getUser());
            mTvCommentContent.setText(productReviewsBean.getContent());
        } else {

            List<Comment> customerReviews = mActive.getCustomerReviews();
            if (customerReviews != null && customerReviews.size() != 0) {
                Comment comment = mActive.getCustomerReviews().get(0);
                mTvActiveCommentor.setText(comment.getUser());
                mTvCommentContent.setText(comment.getContent());
            } else {
                mllCommentContainer.setVisibility(View.GONE);
            }

        }

        mImages.clear();
        mImages.addAll(mActive.getImages());

        mGvActive.setAdapter(new ActiveImageAdapter(getActivity(), mImages));
        mGvActive.setOnItemClickListener(this);

        int status = mActive.getStatus();

        mLLActive_Operator.setVisibility(View.GONE);
        mBtnDirectShare.setVisibility(View.GONE);
        mRlExecuteScreenshot.setVisibility(View.GONE);
        mRlDetailScreenshot.setVisibility(View.GONE);
        mRlNumScreenshot.setVisibility(View.GONE);
        mBtnDirectShare.setVisibility(View.GONE);
        mBtnFollow.setVisibility(View.INVISIBLE);


        if (mActive.getFollowed() != 1) {
            mBtnFollow.setVisibility(View.VISIBLE);
        }

        if (status == ActiveState.STATE_UNCONFIRM) {//未确认
            mLLActive_Operator.setVisibility(View.VISIBLE);
        }


        if (status == ActiveState.STATE_UNEXECUTE || status == ActiveState.STATE_UNCHECK || status == ActiveState.STATE_PASS || status == ActiveState.STATE_UNPASS) {
            mBtnDirectShare.setVisibility(View.VISIBLE);
        }


        if (status == ActiveState.STATE_UNEXECUTE) {//未执行
            //date
            mRlExecuteScreenshot.setVisibility(View.VISIBLE);


            if (DateUtil.isTheDayAfterDay(HttpHelper.getServerTime(), DateUtil.getDate(mActive.getStarttime()))) {
                mRlNumScreenshot.setVisibility(View.VISIBLE);
                mRlDetailScreenshot.setVisibility(View.VISIBLE);


                if (mActive.getNlike() == 0 || mActive.getNcomment() == 0)
                    new CommonToast(getActivity()).setLayoutGravity(Gravity.CENTER_VERTICAL)
                            .setMessage(getResources().getString(R.string.toast_active_2))
                            .setDuration(CommonToast.DURATION_SHORT).show();

                else if (mActive.getResultScreenshot2() == null) {
                    new CommonToast(getActivity()).setLayoutGravity(Gravity.CENTER_VERTICAL)
                            .setMessage(getResources().getString(R.string.toast_active_3))
                            .setDuration(CommonToast.DURATION_SHORT).show();
                }
            } else {
                mRlNumScreenshot.setVisibility(View.GONE);
                mRlDetailScreenshot.setVisibility(View.GONE);


                if (mActive.getPublishScreenshot() == null)
                    new CommonToast(getActivity()).setLayoutGravity(Gravity.CENTER_VERTICAL)
                            .setMessage(getResources().getString(R.string.toast_active_1))
                            .setDuration(CommonToast.DURATION_SHORT).show();
            }

        }

        if (status == ActiveState.STATE_REFUSE) {
            mBtnFollow.setVisibility(View.INVISIBLE);
        }

        if (status == ActiveState.STATE_PASS || status == ActiveState.STATE_UNPASS || status == ActiveState.STATE_UNCHECK) {
            mRlExecuteScreenshot.setVisibility(View.VISIBLE);
            mRlNumScreenshot.setVisibility(View.VISIBLE);
            mRlDetailScreenshot.setVisibility(View.VISIBLE);
        }

        if (TextUtils.isEmpty(AppContext.getInstance().getProperty("guide")) && mLLActive_Operator.getVisibility() == View.VISIBLE && mBtnReceive.getVisibility() == View.VISIBLE)

            getActivity().getWindow()
                    .getDecorView()
                    .getViewTreeObserver()
                    .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                                getActivity().getWindow()
                                        .getDecorView()
                                        .getViewTreeObserver()
                                        .removeOnGlobalLayoutListener(this);
                            } else {
                                getActivity().getWindow()
                                        .getDecorView()
                                        .getViewTreeObserver()
                                        .removeGlobalOnLayoutListener(this);
                            }
                            showGuideView();
                            AppContext.getInstance().setProperty("guide", "true");
                        }
                    });
//
////// TODO: 16/9/23 test!!!!
//        mRlExecuteScreenshot.setVisibility(View.VISIBLE);
//        mRlNumScreenshot.setVisibility(View.VISIBLE);
//        mRlDetailScreenshot.setVisibility(View.VISIBLE);

    }

    public void showGuideView() {

        if (guide != null) {
            return;
        }
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case 1:
                        if (guide != null) {
                            guide.dismiss();
                            srlRefresh.setStopScroll(false);
                        }
                        break;
                }
            }
        };
        GuideBuilder builder = new GuideBuilder();
        builder.setTargetView(mBtnReceive)
                .setAlpha(204)
                .setOverlayTarget(false)
                .setOutsideTouchable(true);
        builder.setOnVisibilityChangedListener(new GuideBuilder.OnVisibilityChangedListener() {
            @Override
            public void onShown() {
            }

            @Override
            public void onDismiss() {
            }
        });
        srlRefresh.setStopScroll(true);
        builder.addComponent(new SimpleComponent(handler));
        guide = builder.createGuide();
        guide.setShouldCheckLocInWindow(true);
        guide.show(getActivity());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tv_link, R.id.tv_link_text, R.id.btn_view_all_commments, R.id.rl_active_help, R.id.btn_follow, R.id.btn_reject_active, R.id.btn_receive_active, R.id.btn_direct_share, R.id.rl_active_execute_screenshot, R.id.rl_active_num_screenshot, R.id.rl_active_detail_screenshot})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_follow:
                followAdviser();
                break;
            case R.id.btn_reject_active:
                refuseActive();
                break;
            case R.id.btn_receive_active:
                attendActive();
                break;

            case R.id.btn_direct_share:
                showWaitDialog("正在下载...");
                downloadPictures(mActive.getImages());
                break;
            case R.id.rl_active_execute_screenshot:
                //待传执行截图
                UIHelper.showExecuteScreenshot(this, CODE_REQUEST, mActive);
                break;
            case R.id.rl_active_num_screenshot:
                //点赞/评论数量图
                UIHelper.showCommentScreenshot(this, CODE_REQUEST, mActive);
                break;
            case R.id.rl_active_detail_screenshot:
                //点赞/评论效果详细图
                UIHelper.showCommentDetailScreenshot(this, CODE_REQUEST, mActive);
                break;
            case R.id.btn_view_all_commments:
                ((IPagerFragment) getParentFragment()).getViewPager().setCurrentItem(1);
                break;
            case R.id.tv_link_text:
                UIHelper.openSysBrowser(getActivity(), mActive.getLink());
                break;
            case R.id.tv_link:
//                UIHelper.openBrowser(getActivity(), mActive.getLinkText(), mActive.getShortLink());
                String url = TextUtils.isEmpty(mActive.getShortLink()) ? mActive.getLink() : mActive.getShortLink();
                UIHelper.openSysBrowser(getActivity(), url);
                break;
            case R.id.rl_active_help:
                UIHelper.openBrowser(getActivity(), "查看帮助", AppConstant.URL_ACTIVE_GUIDE);
                break;
        }
    }

    private void followAdviser() {
        FollowPost post = new FollowPost(mActive.getMediaid(), mActive.getAdvertiserid());
        ApiFactory.getUserApi().followAdviser(post).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        mBtnFollow.setText("已关注");
                        mBtnFollow.setVisibility(View.INVISIBLE);

                    }
                });


    }

    private void refuseActive() {
        if (activeIsEnd()) {
            AppContext.showToast("活动已结束");
            return;
        }
        showWaitDialog();
        ActivePost post = new ActivePost(mActive.getId(), mActive.getMediaid());
        ApiFactory.getUserApi().refuseActive(post).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(getActivity()) {
                    @Override
                    public void onCompleted() {
                        hideWaitDialog();

                        EventBus.getDefault().post(new ActiveStatueRefreshEvent(0));
                        CommonToast com = new CommonToast(getActivity());
                        com.setLayoutGravity(Gravity.CENTER_VERTICAL)
                                .setMessage(getResources().getString(R.string.toast_active_refuse))
                                .setDuration(CommonToast.DURATION_SHORT).show();

                        mLLActive_Operator.setVisibility(View.GONE);
                        mBtnDirectShare.setVisibility(View.GONE);
                        mRlDetailScreenshot.setVisibility(View.GONE);
                        mRlExecuteScreenshot.setVisibility(View.GONE);
                        mRlNumScreenshot.setVisibility(View.GONE);


                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                        AppContext.showToast(e.getMessage());
                    }
                });


    }

    /**
     * 活动是否结束
     *
     * @return ture-end
     */

    private boolean activeIsEnd() {
        String endTime = mActive.getEndtime();
        if (!TextUtils.isEmpty(endTime)) {
            try {
                if (System.currentTimeMillis() + HttpHelper.getOffset() >= DateUtil.getDate(endTime)) {
                    return true;
                }
            } catch (NumberFormatException e) {
                LogUtils.printLogE(e.getMessage());
            }
        }
        return false;
    }

    private void attendActive() {

        if (activeIsEnd()) {
            AppContext.showToast("活动已结束");
            return;
        }
        showWaitDialog();
        ActivePost post = new ActivePost(mActive.getId(), mActive.getMediaid());
        ApiFactory.getUserApi().attendActive(post).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseSubscriber<Result>(getActivity()) {

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        hideWaitDialog();
                    }

                    @Override
                    public void onCompleted() {
                        mLLActive_Operator.setVisibility(View.GONE);
                        hideWaitDialog();
                        EventBus.getDefault().post(new ActiveStatueRefreshEvent(0));
//                        AppContext.showToast("已经参与");
                        // 参与提示
                        textImageLayout.tv.setText(R.string.guideview_active_join);
                        textImageLayout.setGuideImage(R.drawable.activity_join);
                        textImageLayout.closeLayout.setVisibility(View.VISIBLE);
                        textImageLayout.setVisibility(View.VISIBLE);
                    }
                });


    }


    private void downloadPictures(List<String> pictures) {
        Observable.from(pictures).subscribe(new Action1<String>() {
            @Override
            public void call(String url) {
                download(url);
            }
        });

    }

    private void download(String url) {
        ApiFactory.getFileApi().downloadPicture(url).subscribeOn(Schedulers.io())
                .map(new Func1<ResponseBody, String>() {
                    @Override
                    public String call(ResponseBody responseBody) {
                        InputStream is = responseBody.byteStream();
                        String[] urlArr = url.split("/");
                        File filesDir = Environment.getExternalStorageDirectory();
                        File file = new File(filesDir, urlArr[urlArr.length - 1]);
                        if (file.exists()) file.delete();
                        try {
                            FileUtils.writeFile(file, is);
                            return file.getAbsolutePath();
                        } catch (IOException e) {
                            hideWaitDialog();
                        }
                        return null;
                    }
                }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                if (imageFile.size() >= mActive.getImages().size()) {
                    hideWaitDialog();
                    String link = !TextUtils.isEmpty(mActive.getShortLink()) ? mActive.getShortLink() : mActive.getLink();
                    String content = new StringBuilder(mActive.getDesc()).append(" \n").append(mActive.getLinkText()).append(":").append(link).toString();
                    ShareUtils.share9PicsToWXCircle(getActivity(), content, imageFile);
                    imageFile.clear();
                }
            }

            @Override
            public void onError(Throwable e) {
                AppContext.showToast(e.getMessage());
                hideWaitDialog();
            }

            @Override
            public void onNext(String path) {
                if (path != null) {
                    imageFile.add(path);
                }
            }
        });
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//        String imgUrl = mActive.getImages().get(position);
//        mImagePreview.showPreview(view, imgUrl);

        PhotoPreview.builder()
                .setPhotos((ArrayList) mActive.getImages())
                .setCurrentItem(position)
                .setShowDeleteButton(false)
                .start(getActivity(), this);


    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        EventBus.getDefault().post(new ActiveStatueRefreshEvent(0));
        if (requestCode == CODE_REQUEST) {
            switch (resultCode) {
                case CODE_REPONSE_EXECUTE://待执行
                    if (data != null) {
                        Active active = (Active) data.getSerializableExtra(ARGS_RESPONSE);
                        mActive.setPublishScreenshot(active.getPublishScreenshot());
                        mTvActiveExecute.setText(getExecuteNum(1));
                    }
                    break;
                case CODE_RESPONSE_COMMENT:
                    if (data != null) {
                        Active active = (Active) data.getSerializableExtra(ARGS_RESPONSE);
                        mActive.setNcomment(active.getNcomment());
                        mActive.setNlike(active.getNlike());
                        mActive.setResultScreenshot1(active.getResultScreenshot1());
                        mTvCommentNum.setText(getCommentNum(mActive.getNlike(), mActive.getNcomment()));
                    }

                    break;
                case CODE_RESPONSE_DETAIL:
                    if (data != null) {
                        Active active = (Active) data.getSerializableExtra(ARGS_RESPONSE);
                        mActive.setResultScreenshot2(active.getResultScreenshot2());
                        mTvDetail.setText(getDetailNum(mActive.getResultScreenshot2().size()));
                    }

                    break;
            }
        }
    }


    //固定效果
    private Spanned getPaymentOnEffect(String type, double every, int individualLimit, int all) {
        StringBuilder sb = new StringBuilder();
        sb.append("结算方式:正常执行后,每次有效%s你将获得<font color=#f94848>").append(every).append("</font>元,");
        if (individualLimit != 0) {
            sb.append("您最多获得<font color=#f94848>").append(individualLimit).append("</font>次%s收益,");
        }
        if (all != 0) {
            sb.append("活动总%s上限<font color=#f94848>").append(all).append("</font>次");
        }


        return Html.fromHtml(String.format(sb.toString(), type, type, type));
    }

    //固定价格
    private Spanned getPaymentOnPrice(int clickAll, int likeAll, int commentAll, double price) {
        StringBuilder sb = new StringBuilder();
        if (clickAll > 0) {
            sb.append("结算方式:正常执行后,如果有效点击数达到<font color=#f94848>").append(clickAll).append("</font>次,");
        }

        if (likeAll > 0) {
            sb.append("且有效点赞数达到<font color=#f94848>").append(likeAll).append("</font>次,");
        }
        if (commentAll > 0) {
            sb.append("且有效评论数达到<font color=#f94848>").append(commentAll).append("</font>次");
        }
        sb.append("您将获得<font color=#f94848>").append(price).append("</font>元");
        return Html.fromHtml(sb.toString());
    }


    private Spanned getCommentNum(int like, int commentNum) {
        return Html.fromHtml("点赞/评论数量图(点赞:<font color=#f94848>" + like + "</font>,评论数量:<font color=#f94848>" + commentNum + "</font>)");
    }

    private Spanned getExecuteNum(int num) {
        return Html.fromHtml("待传执行截图(" + "<font color=#f94848>" + num + "</font>)");
    }


    private Spanned getDetailNum(int num) {
        return Html.fromHtml("点赞/评论效果详细图(" + "<font color=#f94848>" + num + "</font>)");
    }


    public void nofityCommnetFragment(int groupid, int status, String link, String linktitle, String productid) {
//        Intent intent = new Intent(AppConstant.INTENT_ACTION_COMMENT);
//        intent.putExtra(ActiveCommentFragment.VALUE_GROUD, groupid + "");
//        getActivity().sendBroadcast(intent);
        EventBus.getDefault().post(new ActiveCommentRefreshEvent(groupid + "", status, link, linktitle, productid));

    }


}
